package com.sky.handler;

import com.sky.exception.BaseException;
import com.sky.exception.ChangeEmployeeException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;
import org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 添加员工的用户名重复
     * @param ex
     * @return
     */
    @ExceptionHandler(value = SQLIntegrityConstraintViolationException.class)
    public Result sqlIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException ex){
        //  Duplicate entry 'kings' for key 'employee.idx_username'
        String[] strings = ex.getMessage().split(" ");
        log.error("用户名已经存在！！{}",strings[2]);
        return Result.error("新增员工失败！用户名已经存在！"+strings[2]);
    }

    /**
     * 员工状态修改失败
     * @param ex
     * @return
     */
    @ExceptionHandler(ChangeEmployeeException.class)
    public Result<String> changeEmployeeException(ChangeEmployeeException ex){
        log.error("修改员工状态失败！");
        return Result.error("修改员工状态失败！！！");
    }

    /**
     * 文件上传失败，大小超过限制
     * @param ex
     * @return
     */
    @ExceptionHandler(SizeLimitExceededException.class)
    public Result<String> sizeLimit(SizeLimitExceededException ex){
        log.error("上传失败文件超过最大的size!！");
        return Result.error("上传失败文件超过最大的size!！");
    }



}
